# send_sms.py

import os
from twilio.rest import Client
from twilio.base.exceptions import TwilioRestException
from dotenv import load_dotenv

# 加载 .env 文件中的环境变量
load_dotenv()

# 从环境变量读取 Twilio 凭证
account_sid = os.getenv('TWILIO_ACCOUNT_SID')
auth_token = os.getenv('TWILIO_AUTH_TOKEN')
twilio_number = os.getenv('TWILIO_PHONE_NUMBER')

# 初始化 Twilio 客户端
client = Client(account_sid, auth_token)

def send_sms(to_number: str, body: str):
    """
    发送单条短信
    :param to_number: 接收方手机号（格式：+15551234567）
    :param body: 短信内容
    :return: 是否成功，消息 SID 或错误信息
    """
    try:
        message = client.messages.create(
            body=body,
            from_=twilio_number,
            to=to_number
        )
        print(f"✅ 成功发送到 {to_number} | Message SID: {message.sid}")
        return True, message.sid
    except TwilioRestException as e:
        print(f"❌ 发送失败到 {to_number} | 错误: {e.msg} (Code: {e.code})")
        return False, str(e)
    except Exception as e:
        print(f"❌ 未知错误到 {to_number} | {str(e)}")
        return False, str(e)

def send_bulk_sms(phone_list: list, message_body: str):
    """
    批量发送短信
    :param phone_list: 手机号列表（每个号码应为 +1 开头的国际格式）
    :param message_body: 要发送的内容
    """
    success_count = 0
    fail_count = 0

    for number in phone_list:
        # 格式化号码（去除空格、横线等）
        cleaned_number = ''.join(filter(str.isdigit, number))
        if not cleaned_number.startswith('1'):
            cleaned_number = '1' + cleaned_number
        full_number = '+' + cleaned_number

        success, _ = send_sms(full_number, message_body)
        if success:
            success_count += 1
        else:
            fail_count += 1

    print(f"\n📊 发送完成：成功 {success_count} 条，失败 {fail_count} 条")

# =============================
# 使用示例
# =============================

if __name__ == "__main__":
    # 示例：美国手机号列表（可从数据库或CSV读取）
    us_phone_numbers = [
        # "+1 555-123-4567",
        "+18574247015",
        # "(666) 777-8888",
        # "+1-999-000-1111"
    ]

    # 要发送的消息
    sms_content = """
🎉 欢迎光临 Star KTV！
今晚来唱歌享买一送一小吃优惠！
📍 地址：123 Fun Street, City, State
📞 预订电话：(555) 555-5555
回复 STOP 可退订
    """

    # 执行群发
    send_bulk_sms(us_phone_numbers, sms_content.strip())